<template>
  <v-list-item
    class="px-2 py-0"
    :class="{ 'bg-primary-lighten-5': selected }"
    rounded="lg"
    @click="openInNewTab"
  >
    <!-- 复选框、时间和网站图标 -->
    <template #prepend>
      <div class="d-flex align-center">
        <!-- 复选框 -->
        <v-checkbox
          class="me-1"
          color="primary"
          hide-details
          :model-value="selected"
          :ripple="false"
          @click.stop="item.id && $emit('toggle-select', item.id)"
        />

        <!-- 时间显示 -->
        <div class="time-container me-1 ms-3">
          <span class="visit-time text-caption">
            {{ formatVisitTime(item.visit_time) }}
          </span>
        </div>

        <!-- 网站图标 -->
        <div class="favicon-container me-2">
          <v-avatar class="favicon" size="16">
            <v-img
              v-if="item.favicon_url && !faviconError"
              :alt="item.title || item.url"
              :src="item.favicon_url"
              @error="onFaviconError"
            />
            <v-icon v-else color="grey" :icon="mdiWeb" size="10" />
          </v-avatar>
        </div>
      </div>
    </template>

    <!-- 主要内容 -->
    <div class="flex-grow-1">
      <div class="d-flex align-center">
        <!-- 标题和域名组合 -->
        <div class="title-domain-container flex-grow-1">
          <v-list-item-title class="text-body-2 font-weight-light d-flex align-center">
            <!-- 标题 -->
            <span class="title-text">{{ item.title || extractDomain(item.url) }}</span>
            <!-- 域名紧跟标题 -->
            <span class="domain-text ms-2">{{ extractDomain(item.url) }}</span>
          </v-list-item-title>
        </div>
      </div>
    </div>

    <!-- 操作按钮和访问次数 -->
    <template #append>
      <div class="d-flex align-center ga-2">
        <!-- 访问次数芯片 -->
        <v-chip
          v-if="item.visit_count > 1"
          class="visit-count-chip"
          color="primary"
          size="x-small"
          variant="text"
        >
          {{ t('history.item.visited-times', { count: item.visit_count }) }}
        </v-chip>

        <!-- 操作按钮 -->
        <div class="d-flex ga-1 item-actions">
          <!-- 删除按钮 -->
          <v-btn
            color="error"
            :icon="mdiDelete"
            size="small"
            :title="t('history.item.delete')"
            variant="text"
            @click.stop="item.id && $emit('delete', item.id)"
          />
        </div>
      </div>
    </template>
  </v-list-item>
</template>

<script lang="ts" setup>
import type { BrowsingHistory } from '~types/browsing-history'
import { mdiDelete, mdiWeb } from '@mdi/js'
import { ref } from 'vue'
import { useI18n } from 'vue-i18n'

interface Props {
  item: BrowsingHistory
  selected: boolean
}

interface Emits {
  (e: 'toggle-select', itemId: number): void
  (e: 'delete', itemId: number): void
}

const props = defineProps<Props>()
defineEmits<Emits>()

const { t } = useI18n()

const faviconError = ref(false)

// 处理图标加载错误
function onFaviconError() {
  faviconError.value = true
}

// 提取域名
function extractDomain(url: string) {
  try {
    const urlObj = new URL(url)
    let domain = urlObj.hostname

    // 移除 www. 前缀
    if (domain.startsWith('www.')) {
      domain = domain.slice(4)
    }

    return domain
  } catch {
    // 如果URL解析失败，返回原始URL
    return url
  }
}

// 格式化访问时间 - 统一使用24小时制 HH:MM 格式
function formatVisitTime(timestamp: number) {
  const visitTime = new Date(timestamp)
  const hours = visitTime.getHours().toString().padStart(2, '0')
  const minutes = visitTime.getMinutes().toString().padStart(2, '0')
  return `${hours}:${minutes}`
}

// 在新标签页打开
function openInNewTab() {
  // 这里需要调用主进程的API来在新标签页打开URL
  // 暂时使用window.open作为fallback
  window.open(props.item.url, '_blank')
}
</script>

<style scoped>
/* 最小化自定义样式，最大化使用Vuetify工具类 */

.favicon-container {
  flex-shrink: 0;
}

.time-container {
  flex-shrink: 0;
  min-width: 60px;
}

.visit-time {
  color: rgb(var(--v-theme-on-surface));
  opacity: 0.6;
  white-space: nowrap;
  font-size: 0.7rem;
  font-weight: 300;
}

/* 标题和域名容器 */
.title-domain-container {
  min-width: 0; /* 允许flex子项收缩 */
  overflow: hidden;
}

.title-text {
  flex-shrink: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  min-width: 0;
  opacity: 0.8;
}

.domain-text {
  flex-shrink: 0;
  opacity: 0.6;
  font-size: 0.75rem;
  font-weight: 400;
  white-space: nowrap;
}

.visit-count-chip {
  font-size: 0.65rem !important;
  height: 18px !important;
}

.item-actions {
  opacity: 0;
  transition: opacity 0.3s ease;
}

.v-list-item:hover .item-actions {
  opacity: 1;
}

/* 优化标题字体大小 */
.v-list-item-title {
  font-size: 0.875rem !important;
  line-height: 1.3 !important;
}

.v-list-item-subtitle {
  font-size: 0.75rem !important;
  line-height: 1.2 !important;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .time-container {
    min-width: 60px;
  }

  .visit-time {
    font-size: 0.7rem;
  }
}

@media (max-width: 480px) {
  .domain-text {
    font-size: 0.7rem;
  }

  .time-container {
    min-width: 50px;
  }

  .v-list-item-title {
    font-size: 0.8rem !important;
  }

  .visit-count-chip {
    font-size: 0.6rem !important;
    height: 16px !important;
  }
}
</style>

<i18n>
{
  "en": {
    "history": {
      "item": {
        "open-in-new-tab": "Open in new tab",
        "delete": "Delete this item",
        "visited-times": "Visited {count} times"
      }
    }
  },
  "zhHans": {
    "history": {
      "item": {
        "open-in-new-tab": "在新标签页中打开",
        "delete": "删除此项",
        "visited-times": "访问了 {count} 次"
      }
    }
  }
}
</i18n>
